layui.define(['form','table','laytpl','declAutocompleter'], function (exports) {
    var $ = layui.$,setter=layui.setter,com = layui.com,laytpl=layui.laytpl, request = layui.request,search = layui.router().search,
        form = layui.form,table=layui.table,declAutocompleter=layui.declAutocompleter,fn={
            disabledForm:function ($form) {
                $form.find('input').removeClass('required').removeClass('disabled').attr({'readonly':true});
            },
            showTextarea(input,title){
                var $input = $(input),maxlength=parseInt($input.attr('maxlength'));
                layer.open({
                    type: 1, anim: 1, shade: 0.2, area: ['450px', '300px'], title:title,
                    content: '<div class="enlarge"><textarea class="layui-textarea" id="enlargeText" enter="no" maxlength="'+maxlength+'" placeholder="Ctrl+Enter换行" showLength="#showLengthText">'+$input.val()+'</textarea></div><div class="layui-row t-a-r">(<span id="showLengthText">0</span>/'+$input.attr('maxlength')+')&nbsp;&nbsp;</div>',
                    success: function(layero, index){
                        $enlargeText = $('#enlargeText');
                        $enlargeText.select().bind('input propertychange',function () {
                            fn.showTextLength($(this));
                            fn.checklen($(this),maxlength);
                        });
                        $enlargeText.keyup(function(event){
                            if(!event.shiftKey && event.keyCode == 13){
                                if(event.ctrlKey && event.keyCode == 13){return;}
                                layer.close(index);
                            }
                        });
                        fn.showTextLength($enlargeText);
                    },end:function () {
                        $input.val($enlargeText.val()).select();
                        fn.showTextLength($input);
                    }
                });
            },
            checklen(inpt, maxlen) {
                var str = inpt.val(),len = str.length,realLength = 0;
                for(var i = 0; i < len; i++){
                    let charCode = str.charCodeAt(i);
                    if (charCode >= 0 && charCode <= 128 && charCode != 10){realLength += 1;}else{realLength += 2;}
                    if (realLength > maxlen) {
                        inpt.val(str.substr(0, i));
                        if(inpt.attr('showLength')){
                            fn.showTextLength(inpt);
                        }
                        return;
                    }
                }
            },
            showTextLength(e){$(e.attr('showLength')).html(fn.textLength(e.val()));},
            textLength(value,flag) {
                flag = (!flag)?2:Number(flag);if(com.isEmpty(value)){return 0;}var realLength = 0;var str = value,len = str.length;
                for (var i = 0; i < len; i++){charCode = str.charCodeAt(i);if (charCode >= 0 && charCode <= 128 && charCode != 10) {realLength += 1;}else{realLength += flag;}}
                return realLength;
            },
            removeLastSplit(val) {
                if(com.isNotEmpty(val)){
                    while (true){
                        val = $.trim(val);
                        if('|'==val.substring(val.length-1)){val = val.substring(0,val.length-1);}else{return val;}
                    }
                }
                return '';
            },
           joinElements() {
                var elementsJson = $('#classifyForm').serializeJson();
                var elestr = fn.removeLastSplit(elementsJson.elementVal.join('|'));
                $('#elementstr').val(elestr);
                $('#elementsLen').html(fn.textLength(elestr));
            },
            initPage(){
                // 显示隐藏区域
                $('button[show-element]').click(function () {
                    var $this = $(this),$element = $($this.attr('show-element'));
                    $element.toggle();
                    if($this.find('.iconarrow-').size()>0){
                        $this.html('<i class="iconfont iconfx6-down"></i>');
                    }else{
                        $this.html('<i class="iconfont iconarrow-"></i>');
                    }
                });
                //其他包装
                $('#decOtherPackBtn').click(function () {
                    layer.open({type: 1,anim: 1,shade:0.2,area: ['540px', '450px'],title:'编辑其他包装信息', btnAlign: 'c',
                        content: '<div class="tab-normal tab-sm"><table class="layui-hide" id="dec-other-pack-list" lay-filter="dec-other-pack-tab"></table></div>',
                        yes: function(index, layero){
                            var selectDatas = table.checkStatus('dec-other-pack-list').data;
                            $('#decOtherPacks').val((selectDatas.length>0)?JSON.stringify(selectDatas):'');
                            layer.close(index);
                        }, success: function(layero, index){
                            var packDatas = [],selectDataMap = {};
                            $.each(JSON.parse($('#decOtherPacks').val() || "[]"),function (i,o){selectDataMap[o.packType] = true;});
                            $.each(declAutocompleter.localData2('CUS_MAPPING_PACKAGEKIND_CODE_V')||[],function (i,o) {
                                packDatas.push({'packSeqNo':(i+1),'packQty':0,'packType':o.c,'packTypeName':o.n,'LAY_CHECKED':(selectDataMap[o.c]?true:false)});
                            });
                            table.render({
                                elem: '#dec-other-pack-list',id:'dec-other-pack-list',limit:500,page:false,text:{none:'未加载到数据,请关闭重新打开'},
                                cols:[[
                                    {type: 'checkbox',width:35}
                                    ,{field:'packSeqNo',title:'序号',width:45,align:'center'}
                                    ,{field:'packType',title:'包装材料种类代码',width:120,align:'center'}
                                    ,{field:'packTypeName',title:'包装材料种类名称'}
                                ]]
                                ,data:packDatas
                            });
                        },end:function () {
                            $('#grossWt').select();
                        }
                    });
                });
                //价格说明
                $('#promiseItemBtn').click(function () {
                    layer.open({id:'promiseItemWin',type: 1,anim: 1,shade:0,area: ['600px', '310px'],title:'价格说明',
                        content:$('#promiseItemArea')
                    });
                });
                //业务事项
                $('#cusRemarkBtn').click(function () {
                    layer.open({id:'cusRemarkWin',type: 1,anim: 1,shade:0,area: ['480px', '200px'],title:'业务事项',
                        content:$('#cusRemarkArea')
                    });
                });
                //使用人
                $('#userInfoBtn').click(function () {
                    layer.open({id:'userInfoWin',type: 1,anim: 1,shade:0,area: ['780px', '270px'],title:'编辑使用人信息',
                        content:$('#userInfoArea'),
                        success: function(layero, index){
                            var uiDatas = JSON.parse($('#preDecUserList').val() || "[]");
                            table.render({
                                elem: '#user-info-list',id:'user-info-list',limit:500,page:false,height:220,text:{none:'暂无数据'},
                                cols:[[
                                    {type: 'checkbox',width:35}
                                    ,{type: 'numbers',width:35,align:'center'}
                                    ,{field:'useOrgPersonCode',title:'使用单位联系人'}
                                    ,{field:'useOrgPersonTel',title:'使用单位联系电话'}
                                ]]
                                ,data: uiDatas || []
                            });
                        }
                    });
                });
                //特殊业务标识
                $('#specDeclFlagBtn').click(function () {
                    layer.open({id:'specDeclFlagWin',type: 1,anim: 1,shade:0,area: ['510px', '200px'],title:'特殊业务标识',
                        content:$('#specDeclFlagArea')
                    });
                });
                //检验检疫签证申报要素
                var nreqContentDatas = [];
                $('#reqContentBtn').click(function () {
                    if(nreqContentDatas.length==0){
                        var reqContentDatas = declAutocompleter.localData1('REQ_CONTENT');
                        if(reqContentDatas){
                            $.each(reqContentDatas,function (i,o){nreqContentDatas.push({'appCertCode':o.c,'appCertName':o.n,'applOri':'1','applCopyQuan':'2'});});
                            table.render({
                                elem: '#req-content-list',id:'req-content-list',limit:500,page:false,height:317,text:{none:'检验检疫签证申报要素未加载完成请稍后重试'},
                                cols:[[
                                    {type: 'checkbox',width:35,fixed:true}
                                    ,{type: 'numbers',width:35,align:'center',title:'序号'}
                                    ,{field:'appCertCode',width:80,title:'证书代码',align:'center'}
                                    ,{field:'appCertName',width:240,title:'证书名称'}
                                    ,{field:'applOri',width:173,title:'正本数量',templet:'#applOriTemp'}
                                    ,{field:'applCopyQuan',width:173,title:'副本数量',templet:'#applCopyQuanTemp'}
                                ]]
                                ,data: nreqContentDatas
                            });
                        }
                    }
                    layer.open({id:'reqContentWin',type: 1,anim: 1,shade:0,area: ['760px', '560px'],title:'检验检疫签证申报要素',content:$('#reqContentArea'),
                        success: function(layero, index){
                            var decRequestCerts = JSON.parse($('#decRequestCert').val() || "[]");
                            if(decRequestCerts.length>0){
                                var decRequestCertMap = {};
                                $.each(decRequestCerts,function (i,o) {decRequestCertMap[o.appCertCode] = o;});
                                var reqConDatas = table.cache["req-content-list"];
                                for(var i=0;i< reqConDatas.length;i++){
                                    var index = reqConDatas[i]['LAY_TABLE_INDEX'];
                                    reqConDatas[i]["LAY_CHECKED"] = false;
                                    $('#reqContentArea .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', false);
                                    $('#reqContentArea .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().removeClass('layui-form-checked');
                                    var itemData = decRequestCertMap[reqConDatas[i].appCertCode];
                                    if(itemData){
                                        reqConDatas[i]["LAY_CHECKED"] = true;
                                        $('#reqContentArea .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                        $('#reqContentArea .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                        $('#applOri'+reqConDatas[i].appCertCode).val(itemData.applOri);
                                        $('#applCopyQuan'+reqConDatas[i].appCertCode).val(itemData.applCopyQuan);
                                    }
                                }
                            }
                        }
                    });
                });
                //查看归类
                $('#againProduct').click(function () {
                    var $codeTs = $('#codeTs'),codeTs=$.trim($codeTs.val()),ocodeTs=$.trim($codeTs.attr('h_code')||'');
                    if(codeTs.length!=10){$codeTs.val('');return;}
                    request.get('system/customsCode/codeDetail/'+codeTs).then(res =>{
                        if(res.data != null){
                            var data = res.data,hsCode=data.hsCode,elements=data.elements || [],ciqCodes=data.ciqCodes || [];
                            //产品表单
                            form.val('productForm',{'unit1':hsCode.unitCode,'unit1Name':hsCode.unitName,'unit2':hsCode.sunitCode,'unit2Name':hsCode.sunitName,'csc':hsCode.csc,'iaqr':hsCode.iaqr});
                            if(com.isEmpty($('#gunitName').val())){
                                form.val('productForm',{'gunit':hsCode.unitCode,'gunitName':hsCode.unitName});
                            }
                            if(com.isNotEmpty(hsCode.sunitCode)){
                                $('#qty2').attr({'readonly':null}).removeClass('disabled');
                            }else{
                                $('#qty2').val('').attr({'readonly':true}).addClass('disabled');
                            }
                            //归类表单
                            $('#classifyForm').find('input').val('');//清空表单数据
                            form.val('classifyForm',{'selectCodeTs':hsCode.id+'-'+hsCode.name,'goodsName':(com.isNotEmpty($('#gname').val())?$('#gname').val():hsCode.name)});
                            //已经填写的申报要素
                            var oldSpecs = $('#gspec').val().split('|');
                            if(parseInt(oldSpecs[0])>=0&&parseInt(oldSpecs[0])<=4){$('#brandTypeCode').val(oldSpecs[0]);}
                            if(parseInt(oldSpecs[1])>=0&&parseInt(oldSpecs[1])<=3){$('#expDiscountCode').val(oldSpecs[1]);}
                            if("I"==$('#cusIEFlag').val()){//进口
                                $('#expDiscountCode').val('3');
                            }
                            //赋值文本
                            if(com.isNotEmpty($('#brandTypeCode').val())){
                                var json = declAutocompleter.findByLocalData1ByCode('BRAND_TYPE',$('#brandTypeCode').val());
                                $('#brandType').val(json.n);
                            }
                            if(com.isNotEmpty($('#expDiscountCode').val())){
                                var json = declAutocompleter.findByLocalData1ByCode('EXP_DISCONUNT',$('#expDiscountCode').val());
                                $('#expDiscount').val(json.n);
                            }
                            //申报要素
                            var nelements = [],isSetVal=(codeTs==ocodeTs);
                            console.log(codeTs);
                            console.log(ocodeTs);
                            for (var i=2;i<elements.length;i++){
                                var item = elements[i];
                                if(isSetVal){
                                    item.val = com.removeNull(oldSpecs[i]);
                                }
                                nelements.push(item);
                            }
                            laytpl($('#elementTemp').html()).render(nelements,function (html) {
                                $('#elementView').html(html);
                            });
                            layer.open({id:'classifyWin',type: 1,anim: 1,shade:0,area: ['900px', 'auto'],title:'商品规范申报-商品申报要素',
                                content:$('#classifyArea'),
                                success: function(layero, index){
                                    fn.joinElements();
                                }
                            });
                        }else{
                            com.tipsMessage('无此商品编码',$codeTs);
                        }
                    });
                });
                //随附单据
                $('#decDocBtn').click(function () {
                    layer.open({id:'decDocContentWin',type: 1,anim: 1,shade:0,area: ['780px', 'auto'],title:'随附单据编辑',
                        content:$('#decDocContentArea')
                    });
                });
            },
            renderProducts:function (data){
                var productFull = $('body').hasClass('product-full');
                table.render({
                    elem: '#product-list',id:'product-list',limit:500,page:false,
                    height:productFull?('full-'+($('#productForm').height()+100)):154,text:{none:'无商品信息'},
                    cols:[[
                        {type: 'radio',width:35, fixed: true}
                        ,{field:'gno',title:'项号',width:35,align:'center', fixed: true}
                        ,{field:'contrItem',title:'备案序号',width:60}
                        ,{field:'codeTs',title:'商品编号',width:75,align:'center'}
                        ,{field:'ciqName',title:'检验检疫名称',width:90}
                        ,{field:'gname',title:'商品名称',width:130}
                        ,{field:'gspec',title:'规格型号',width:(productFull)?null:340}
                        ,{field:'gqty',title:'成交数量',width:90,align:'money'}
                        ,{field:'gunitName',title:'成交单位',width:60,align:'center'}
                        ,{field:'declPrice',title:'单价',width:70,align:'right'}
                        ,{field:'declTotal',title:'总价',width:80,width:85,align:'money'}
                        ,{field:'tradeCurrName',title:'币制',width:45,align:'center'}
                        ,{field:'cusOriginCountryName',title:'原产国',width:60,align:'center'}
                        ,{field:'destinationCountryName',title:'最终目的国',width:70,align:'center'}
                        ,{field:'dutyModeName',title:'征免方式',width:70,align:'center'}
                        ,{field:'csc',title:'监管要求',width:70,templet:'#cscTemp'}
                    ]]
                    ,data: data
                });
                table.render({
                    elem: '#trn-product-list',id:'trn-product-list',limit:500,page:false,
                    height:180,text:{none:'暂无商品信息'},
                    cols:[[
                        {type: 'checkbox',width:35, fixed: true}
                        ,{field:'gno',title:'商品序号',width:56,align:'center', fixed: true}
                        ,{field:'codeTs',title:'商品编号',width:80,align:'center'}
                        ,{field:'gname',title:'商品名称',width:260}
                        ,{field:'gqty',title:'成交数量',width:100,align:'money'}
                    ]]
                    ,data: data
                });

                //生成检验检疫货物规格
                var goodsTargetInputArg = ['stuff','prodValidDt','prodQgp','engManEntCnm','goodsSpec','goodsModel','goodsBrand','produceDate','prodBatchNo','mnufctrRegNo'];
                //产品行选择监听
                table.on('row(product-tab)', function(obj){
                    var inx = obj.tr.attr('data-index');
                    $.each(table.cache["product-list"],function (i,o) {
                        var index= o['LAY_TABLE_INDEX'],$tr = $('.layui-table-view[lay-id="product-list"] tr[data-index=' + index + ']');
                        var $itemRadio = $tr.find('input[type="radio"]');
                        if(inx==index){
                            o["LAY_CHECKED"] = true;
                            $itemRadio.prop('checked', true);
                            $itemRadio.next().addClass('layui-form-radioed');
                            $itemRadio.next().find('.layui-anim ').remove();
                            $itemRadio.next().append('<i class="layui-anim layui-icon layui-anim-scaleSpring"></i>');
                            $tr.addClass('layui-table-click');
                        }else{
                            o["LAY_CHECKED"] = false;
                            $itemRadio.prop('checked', false);
                            $itemRadio.next().removeClass('layui-form-radioed');
                            $itemRadio.next().find('.layui-anim ').remove();
                            $itemRadio.next().append('<i class="layui-anim layui-icon"></i>');
                            $tr.removeClass('layui-table-click');
                        }
                    });
                    var productData = obj.data;
                    productData['gNoTo'] = '';
                    form.val('productForm',productData);
                    $('#codeTs').attr({'h_code':productData.codeTs});

                    var goodsTargetInputs = [];
                    $.each(goodsTargetInputArg,function (i,o) {if(com.isNotEmpty(productData[o])){goodsTargetInputs.push(pd[o]);}});
                    $('#goodsTargetInput').val(goodsTargetInputs.join(';'));

                    if(com.isNotEmpty(productData.unit2Name)){$('#qty2').attr({'readonly':null}).removeClass('disabled');}else{$('#qty2').attr({'readonly':true}).addClass('disabled');}
                });
            },
            renderDocFiles:function(){
                table.render({
                    elem: '#doc-content-list',where:{'declarationId':$('#id').val()},text:{none:'未上传任何文件'}
                    ,url:'declare/docFile/list',method: 'post',height: 294,response:{msgName:'message',statusCode: '1'}
                    ,page: false,limit:500,id:'doc-content-list'
                    ,cols: [[
                        {field:'attTypeCodeName',width:200,title: '文件类别',align:'center'}
                        ,{field:'name', width:306,title: '文件名称',align:'center',templet:'#previewTemp'}
                        ,{field:'attEdocNo',width:270,title: '单据编号',align:'center'}
                    ]]
                });
            },
            async init(){
                let declareId = search.id;
                request.get('/declare/declaration/detail',{id:declareId}).then(res =>{
                    let data = res.data;
                    form.val('decForm',data.declaration);
                    form.val('businessTypeForm',{'businessType':data.declaration.businessType});
                    form.val('promiseItemForm',data.declaration);
                    form.val('relationForm',data.declaration);
                    form.val('reqContentForm',data.declaration);
                    form.val('trnHeadForm',data.declTrnHead);
                    //业务事项
                    var cusRemarks = (data.declaration.cusRemark || '0,0,0,0,0').split(',');
                    form.val('cusRemarkForm',{'taxPaperless':cusRemarks[0]=='1','independentTax':cusRemarks[1]=='1','cusRemark1':cusRemarks[2]=='1','cusRemark6':cusRemarks[3]=='1','cusRemark7':cusRemarks[4]=='1'});
                    //特殊业务标识
                    var specDeclFlag = (data.declaration.specDeclFlag || '0,0,0,0,0,0,0').split(',');
                    form.val('specDeclFlagForm',{'specDeclFlag1':specDeclFlag[0]=='1', 'specDeclFlag2':specDeclFlag[1]=='1', 'specDeclFlag3':specDeclFlag[2]=='1', 'specDeclFlag4':specDeclFlag[3]=='1', 'specPassFlag1':specDeclFlag[4]=='1', 'specPassFlag3':specDeclFlag[5]=='1', 'specPassFlag4':specDeclFlag[6]=='1',});
                    //产品明细
                    fn.renderProducts(data.products || []);
                    form.render();
                    $.each($('input[showLength]'),function (i,o) {fn.showTextLength($(o));});

                    //特殊业务标识显示
                    var specDeclFlagInputs = [];
                    $('#specDeclFlagForm').find('input[type="checkbox"]:checked').each(function (i,o) {
                        specDeclFlagInputs.push($(o).attr('title'));
                    });
                    $('#specDeclFlagInput').val(specDeclFlagInputs.join(','));
                    //所需单证名称展示
                    var decRequestCerts = JSON.parse($('#decRequestCert').val() || "[]");
                    if(decRequestCerts.length>0) {
                        var appCertNames = [];
                        $.each(decRequestCerts, function (i, o){appCertNames.push(o.appCertName);});
                        $('#appCertName').val(appCertNames.join(','));
                    }
                    //  单据附件
                    fn.renderDocFiles();
                }).catch(()=>{
                    location.hash = '/declare/list';
                });
                declAutocompleter.init();
                fn.initPage();
            }
        };
    fn.disabledForm($('#decForm'));
    fn.disabledForm($('#productForm'));
    fn.init();
    exports('trustDecDetail', fn);
});